//
//  CTPersonalMessageView.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/6/10.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTPersonalMessageView.h"
#import "CTDebugManager.h"
#import "CTHeader.h"
#import "CTPersonalMessageCell.h"
#import "CTUserItem.h"
#import "CTUser.h"
#import "CTFile.h"
#import "CTMessageItems.h"
#import "CTDataGenerator.h"
#import "CTAppLanguage.h"
#import "RefreshControl.h"
#import "CTTextManager.h"


@interface CTPersonalMessageView ()<UITableViewDataSource,UITableViewDelegate,RefreshControlDelegate,CTPersonalMessageCellDelegate>
{
    UITableView * personalMesgTableView;
    
    NSArray * personalMessageListArr;
    
    UIView * noDataView;
    
    RefreshControl  *refreshControl;
}

@end


@implementation CTPersonalMessageView
@synthesize delegate;

- (void)dealloc
{
    delegate = nil;
 
    [noDataView removeFromSuperview];
    noDataView = nil;
    
    refreshControl = nil;
    
    [personalMesgTableView removeFromSuperview];
    personalMesgTableView = nil;
    
    personalMessageListArr = nil;
    
    [CTDebugManager showErrorLogInfo:@"dealloc : CTPersonalMessageView Is Removed!!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.frame = CGRectMake(0, 64, CT_HEADER_SCREEN_WIDTH, CT_HEADER_SCREEN_HEIGHT - 64 - 50);
        self.backgroundColor = [UIColor clearColor];
        
        
        [self createSubviews];
        [self creatNoDataView];
    }
    return self;
}



- (void)createSubviews
{
    personalMesgTableView = [[UITableView alloc]initWithFrame:self.bounds style:UITableViewStylePlain];
    personalMesgTableView.delegate = self;
    personalMesgTableView.dataSource = self;
    personalMesgTableView.showsVerticalScrollIndicator = NO;
    personalMesgTableView.rowHeight = 68.0f;
    personalMesgTableView.backgroundColor = [UIColor redColor];
    personalMesgTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    personalMesgTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    personalMesgTableView.backgroundColor = [UIColor clearColor];
    [personalMesgTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self addSubview:personalMesgTableView];
    
    
    /*
     *** refresh control
     */
    refreshControl = [[RefreshControl alloc] initWithScrollView:personalMesgTableView delegate:self];
    refreshControl.topEnabled = YES;
    refreshControl.bottomEnabled = NO;
    refreshControl.enableInsetBottom = 60;
}


-(void)creatNoDataView
{
    
    noDataView = [[UIView alloc] initWithFrame:CGRectMake(0,(CT_HEADER_SCREEN_HEIGHT - 64-50 - 184)/2.0, CT_HEADER_SCREEN_WIDTH, 184)];
    noDataView.backgroundColor = [UIColor clearColor];
    //   noDataView.center = self.center;
    noDataView.hidden = YES;
    [self addSubview:noDataView];
    
    UIImageView * notLoginInImageView = [[UIImageView alloc] initWithFrame:CGRectMake((CT_HEADER_SCREEN_WIDTH - 90.5)/2.0, 0, 90.5, 108)];
    notLoginInImageView.image = [UIImage imageNamed:@"wuneirong"];
    [noDataView addSubview:notLoginInImageView];
    
    UILabel * remindLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,notLoginInImageView.frame.size.height + 15.0, CT_HEADER_SCREEN_WIDTH, 18.0)];
    remindLabel.textAlignment = NSTextAlignmentCenter;
    remindLabel.font = [UIFont systemFontOfSize:18.0];
    remindLabel.text = [CTAppLanguage localizedStringForKey:@"message_no_noti" withValue:nil withTable:@"Language"];
    remindLabel.textColor = [UIColor colorWithRed:164/255.0 green:164/255.0 blue:164/255.0 alpha:1.0];
    [noDataView addSubview:remindLabel];
    
    
}



#pragma mark-UITableViewDataSource
//分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return personalMessageListArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    CTPersonalMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[CTPersonalMessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.delegate = self;
    }
    cell.item = [personalMessageListArr objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    tableView.rowHeight = cell.bounds.size.height;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
    CTMessageListItem * itm = [personalMessageListArr objectAtIndex:indexPath.row];
    [self cancelIsReadAction:itm];
    
    
    if ([self.delegate respondsToSelector:@selector(selectPersonalMessageAction:)]) {
        [self.delegate selectPersonalMessageAction:[personalMessageListArr objectAtIndex:indexPath.row]];
    }
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate respondsToSelector:@selector(deletePersonalMessageAction:)]) {
        [self.delegate deletePersonalMessageAction:[personalMessageListArr objectAtIndex:indexPath.row]];
    }
}



#pragma mark - action -

-(void)cancelIsReadAction:(CTMessageListItem *)itm
{
    @try {
        if ([itm.isRead isEqualToString:@"1"]) {
            return;
        }
        
        NSString * fileNameStr = @"visitor";
        CTUserItem * userItem = [CTUser userInfo];
        if (userItem != nil)fileNameStr = [NSString stringWithFormat:@"%@.plist",userItem.uid];
        NSMutableDictionary * infoMutableDic = [CTFile getDicFile:fileNameStr fromDoc:CTFileDocLibrary fromPath:@"cacheData/message/personalMesg"];
        
        if (infoMutableDic != nil || infoMutableDic.count != 0) {
            
            NSArray * listArray = (NSArray *)[infoMutableDic objectForKey:@"list"];
            
            for (NSMutableDictionary * infoDic in listArray) {
                NSString * noticeID = [NSString stringWithFormat:@"%@",[infoDic objectForKey:@"notice_id"]];
                if ([itm.notice_id isEqualToString:noticeID]) {
                    [infoDic setObject:@"1" forKey:@"isRead"];
                    break;
                }
            }
        }
        
        [CTFile cacheDicFile:infoMutableDic fileName:fileNameStr saveDoc:CTFileDocLibrary savePath:@"cacheData/message/personalMesg"];
        personalMessageListArr = [CTDataGenerator generatePersonalMessageListItems];
        [personalMesgTableView reloadData];
    }
    @catch (NSException *exception) {
        
    }
}





#pragma mark - action & delegate -

-(void)imageClicked:(CTPersonalMessageCell *)view withItem:(CTMessageListItem *)itm
{
    [self cancelIsReadAction:itm];
    
    if ([self.delegate respondsToSelector:@selector(personMesgImageClicked:withItem:)]) {
        [self.delegate personMesgImageClicked:self withItem:itm];
    }
    
}

-(void)refresh
{
    [refreshControl startRefreshingDirection:RefreshDirectionTop];
}

-(void)refreshPullDownEnd
{
    [refreshControl finishRefreshingDirection:RefreshDirectionTop];
}

-(void)refreshPullUpEnd
{
    [refreshControl finishRefreshingDirection:RefreshDirectionBottom];
}

-(void)reloadData
{
    [personalMesgTableView reloadData];
}

#pragma mark - refresh control delegate -

- (void)refreshControl:(RefreshControl *)refreshControl didEngageRefreshDirection:(RefreshDirection) direction
{
    if (direction == RefreshDirectionTop) {
        if ([self.delegate respondsToSelector:@selector(refreshControlPullDown:)]) {
            [self.delegate refreshControlPullDown:self];
        }
        
    }else{
        if ([self.delegate respondsToSelector:@selector(refreshControlPullUp:)]) {
            [self.delegate refreshControlPullUp:self];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y >= 0.0 && scrollView.contentOffset.y < 80) {
        [refreshControl finishRefreshingDirection:RefreshDirectionTop];
    }
    if (scrollView.contentOffset.y + scrollView.frame.size.height<= scrollView.contentSize.height && scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height - 80) {
        [refreshControl finishRefreshingDirection:RefreshDirectionBottom];
    }
    
    if (scrollView.contentOffset.y + scrollView.frame.size.height <= scrollView.contentSize.height+50) {
        refreshControl.isPullDown = YES;
    }else{
        refreshControl.isPullDown = NO;
    }
    
}


#pragma mark -setter -

-(void)setMessageListArr:(NSArray *)listArr
{
    @try {
        NSString * fileNameStr = @"visitor";
        CTUserItem * userItem = [CTUser userInfo];
        if (userItem != nil)fileNameStr = [NSString stringWithFormat:@"%@.plist",userItem.uid];
        NSMutableDictionary * infoMutableDic = [CTFile getDicFile:fileNameStr fromDoc:CTFileDocLibrary fromPath:@"cacheData/message/personalMesg"];
        
        if ([[NSString stringWithFormat:@"%@",[infoMutableDic objectForKey:@"next_page"]] isEqualToString:@"1"])refreshControl.bottomEnabled = YES;
        else refreshControl.bottomEnabled = NO;
    }
    @catch (NSException *exception) {
        refreshControl.bottomEnabled = NO;
    }
    
    
    
    personalMessageListArr = listArr;
    if (personalMessageListArr.count == 0) {
        noDataView.hidden = NO;
    }else{
        noDataView.hidden = YES;
    }
    [personalMesgTableView reloadData];
}

-(void)setViewHide:(BOOL)hideView
{
    self.hidden = hideView;
}



@end
